<template>
  <el-card
    shadow="always"
    :body-style="{
      padding: '20px',
      height: 'calc(calc(100vh - 170px) / 2 - 58px)',
    }"
  >
    <template #header>
      <el-row>
        <el-col :span="12"
          ><span style="font-size: larger; font-weight: bold"
            >【{{ projectStore.selectedProject.name }}】中的模块信息</span
          ></el-col
        >
        <el-col :span="12" style="text-align: right">
          <el-button
            type="primary"
            size="default"
            @click="saveModules"
            :disabled="projectId === '-1'"
          >
            <el-icon><Finished /></el-icon> 保存模块变更</el-button
          ></el-col
        >
      </el-row>
    </template>
    <el-row :gutter="20">
      <el-col :span="12" :offset="0">
        <el-card shadow="always" :body-style="{ padding: '20px' }">
          <template #header>
            <div>
              <span style="font-weight: bold">项目中的模块</span>
            </div>
          </template>
          <draggable
            style="
              height: calc(calc(100vh - 170px) / 2 - 158px);
              overflow-y: auto;
            "
            :list="modulesInProject"
            :item-key="generateUid"
            :group="{ name: 'name' }"
          >
            <template #item="{ element }">
              <el-tag
                size="large"
                effect="dark"
                closable
                @close="removeModule(element)"
                @dblclick="viewModule(element)"
              >
                <div class="tag-content">
                  <el-avatar
                    :size="16"
                    :src="element.type === 'web' ? webPic : apiPic"
                  />
                  <span style="margin-left: 5px">{{ element.name }}</span>
                </div></el-tag
              >
            </template>
          </draggable>
        </el-card></el-col
      >
      <el-col :span="12" :offset="0">
        <el-card shadow="always" :body-style="{ padding: '20px' }">
          <template #header>
            <div>
              <span style="font-weight: bold">所有模块列表</span>
            </div>
          </template>
          <draggable
            style="
              height: calc(calc(100vh - 170px) / 2 - 158px);
              overflow-y: auto;
            "
            :list="allModules"
            :item-key="generateUid"
            :group="{ name: 'name', pull: 'clone', put: 'false' }"
          >
            <template #item="{ element }">
              <el-tag
                size="large"
                effect="dark"
                @close="removeModule(element)"
                @dblclick="viewModule(element)"
              >
                <div class="tag-content">
                  <el-avatar
                    :size="16"
                    :src="element.type === 'web' ? webPic : apiPic"
                  />
                  <span style="margin-left: 5px">{{ element.name }}</span>
                </div></el-tag
              >
            </template>
          </draggable>
        </el-card></el-col
      >
    </el-row>
  </el-card>
</template>

<script setup lang="ts">
import { listModuleApi } from "@/api/sunnymodule";
import {
  listModulesInProjectApi,
  updateProjectApi,
  listProjectsApi,
} from "@/api/sunnyproject";
import type { SunnyModule } from "@/types/sunnyModule/type";
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";
import { onBeforeRouteUpdate } from "vue-router";
import draggable from "vuedraggable";
import { Finished } from "@element-plus/icons-vue";
import { useProjectStore } from "@/stores/sunnyProjectStore";
import { uniqueId } from "xe-utils";
import router from "@/router";
import { useModuleStore } from "@/stores/sunnyModuleStore";

//由于获取projectId是从路由url中取得，所以是个字符串，并不是number，如果写number，可以用，只是有个警告。
const props = defineProps<{ projectId: string }>();

const modulesInProject = ref<SunnyModule[]>([]);

const allModules = ref<SunnyModule[]>([]);

const webPic = ref(new URL("@/assets/img/web.png", import.meta.url).href);
const apiPic = ref(new URL("@/assets/img/api.png", import.meta.url).href);

const projectStore = useProjectStore();

const moduleStore = useModuleStore();

onMounted(() => {
  listModules(Number(props.projectId));
});

onBeforeRouteUpdate((to) => {
  listModules(Number(to.params.projectId));
});

function listModules(projectId: number) {
  //将字符串转为number
  if (projectId < 0) {
    modulesInProject.value.length = 0;
  } else {
    listModulesInProjectApi(projectId).then(({ data }) => {
      modulesInProject.value = data;
    });
  }
  listModuleApi().then(({ data }) => {
    allModules.value = data;
  });
}

function removeModule(module: SunnyModule) {
  //选择只做前端处理，后端在拖拽完成之后一次性提交。
  modulesInProject.value.splice(modulesInProject.value.indexOf(module), 1);
}

//修改模块的变更
function saveModules() {
  console.log("当前项目中的模块列表是", modulesInProject.value.toString());
  listProjectsApi().then(({ data }) => {
    //当前的项目,通过获取完整的项目列表，然后匹配当前路由中的id来找到这个project
    let nowProject = data.find((element) => {
      return element.id === Number(props.projectId);
    })!;
    //修改project中的moduleList数据
    nowProject.moduleList = modulesInProject.value
      .map((element) => element.id)
      .toString();
    updateProjectApi(nowProject)
      .then(() => {
        ElMessage.success("更新模块信息成功");
      })
      .then(() => {
        //跳转路由到project界面，从而触发project组件中projectList的更新
        router.push({ name: "project" });
      });
  });
}

/**基于modulename生成一个唯一的编号，name-1 */
function generateUid(module: SunnyModule) {
  return uniqueId(`${module.name}-`);
}

function viewModule(element: SunnyModule) {
  moduleStore.selectedModule = element;
  router.push({
    name: "caseInModule",
    params: { moduleId: element.id },
  });
}
</script>

<style scoped>
.el-col {
  padding: 2px 5px;
}

.module-title {
  font-size: larger;
  font-weight: bold;
  margin-bottom: 10px;
}

.el-tag {
  margin: 5px 5px;
}

.tag-content {
  display: flex;
  align-items: center;
}
</style>
